package com.example.droidmotion

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.fragment.app.Fragment
import com.example.droidmotion.common.replaceFragmentInActivity
import com.example.droidmotion.fragment.RecyclerFragment
import com.example.droidmotion.listener.BottomNavigationViewListener
import com.example.droidmotion.listener.OnBackPressedListener
import com.google.android.material.bottomnavigation.BottomNavigationView

class MainActivity : AppCompatActivity(), BottomNavigationViewListener {

    private lateinit var bottomNavigation: BottomNavigationView

    override fun onCreate(savedInstanceState: Bundle?) {
        setTheme(R.style.AppTheme)
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        setupFragment(RecyclerFragment.newInstance())
        bottomNavigation = findViewById(R.id.bottom_navigation)
    }

    private fun setupFragment(fragment: Fragment) {
        supportFragmentManager.findFragmentById(R.id.fragment_container)
            ?: replaceFragmentInActivity(fragment, R.id.fragment_container)
    }

    override fun hideBottomNavigationView() {
        if (bottomNavigation.translationY == 0f)
            bottomNavigation.animate()
                .translationY(bottomNavigation.height.toFloat())
                .setDuration(250)
                .start()
    }

    override fun showBottomNavigationView() {
        if (bottomNavigation.translationY >= bottomNavigation.height.toFloat())
            bottomNavigation.animate()
                .translationY(0f)
                .setDuration(400)
                .start()
    }

    override fun onBackPressed() {
        val fragmentList = supportFragmentManager.fragments
        var proceedToSuper = true
        for (fragment in fragmentList) {
            if (fragment is OnBackPressedListener) {
                proceedToSuper = false
                (fragment as OnBackPressedListener).onBackPressed()
            }
        }
        if (proceedToSuper) super.onBackPressed()
    }
}